package stardust.product.platform.webc.spi.servlet;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import stardust.product.platform.webc.RenderForward;
import stardust.product.platform.webc.RenderHandle;
import stardust.product.platform.webc.WebcConfig;
import stardust.product.platform.webc.WebcException;
import stardust.product.platform.webc.WebcRequestHandler;
import stardust.product.platform.webc.WebcResourceReference;


public class JsonRenderer implements RenderHandle
{

  public void render(WebcRequestHandler request, WebcResourceReference reference, String uri, RenderForward forward)
  {
    ServletWebcRequestHandler req = (ServletWebcRequestHandler) request;

    GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting();
    //builder.serializeNulls(); // TODO 基站物业不使用
    builder.serializeSpecialFloatingPointValues();

    Gson gson = builder.create();
    String jsonText = gson.toJson(forward.getResult());

    try
    {
      req.getResponse().setContentType("text/plain; charset=" + req.getWebcContext().getConfig().getParameter().get(WebcConfig.CFG_CHARACTER_ENCODING));
      req.getResponse().getWriter().write(jsonText);
    }
    catch (IOException e)
    {
      throw new WebcException("访问资源[" + uri + " -> " + reference.getUri() + "]时发生错误，调用处理程序成功，但执行渲染失败。", e);
    }
  }
}
